import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:mobile_scanner/mobile_scanner.dart';
import '../service/book_provider.dart';
import '../model/book.dart';
import 'addbook_view.dart';

class ScanScreen extends StatefulWidget {
  @override
  _ScanScreenState createState() => _ScanScreenState();
}

class _ScanScreenState extends State<ScanScreen> {
  MobileScannerController cameraController = MobileScannerController();
  String? scannedIsbn;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('扫描ISBN'),
        actions: [
          IconButton(
            icon: ValueListenableBuilder(
              valueListenable: cameraController.torchState,
              builder: (context, state, child) {
                switch (state) {
                  case TorchState.off:
                    return Icon(Icons.flash_off, color: Colors.grey);
                  case TorchState.on:
                    return Icon(Icons.flash_on, color: Colors.yellow);
                }
              },
            ),
            onPressed: () => cameraController.toggleTorch(),
          ),
        ],
      ),
      body: MobileScanner(
        controller: cameraController,
        onDetect: (capture) {
          final List<Barcode> barcodes = capture.barcodes;
          for (final barcode in barcodes) {
            if (barcode.rawValue != null && scannedIsbn != barcode.rawValue) {
              setState(() {
                scannedIsbn = barcode.rawValue;
              });
              _processScannedIsbn(barcode.rawValue!);
            }
          }
        },
      ),
    );
  }

  Future<void> _processScannedIsbn(String isbn) async {
    final bookProvider = Provider.of<BookProvider>(context, listen: false);
    
    // 检查图书是否已存在
    final existingBook = await bookProvider.getBookByIsbn(isbn);
    
    if (existingBook != null) {
      // 显示已有图书信息
      _showBookInfo(existingBook);
    } else {
      // 跳转到添加图书页面
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => AddBookScreen(isbn: isbn),
        ),
      );
    }
  }

  void _showBookInfo(Book book) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(book.title),
        content: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          children: [
            if (book.coverUrl != null)
              Image.network(book.coverUrl!),
            SizedBox(height: 10),
            Text('作者: ${book.author}'),
            if (book.publisher != null)
              Text('出版社: ${book.publisher}'),
            if (book.publishDate != null)
              Text('出版日期: ${book.publishDate}'),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text('关闭'),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    cameraController.dispose();
    super.dispose();
  }
}